//
//  MeterDetailViewController.m
//  OST
//
//  Created by mac on 13-7-11.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "MeterDetailViewController.h"
#import "MeterStatusData.h"
#import "GlobalVar.h"
#import "wis.h"
#import "Utitlity.h"

@interface MeterDetailViewController (){
    NSString *ipUrl;
}

@end

@implementation MeterDetailViewController
@synthesize data;
@synthesize labelA,labelKwh,labelV,labelW;
@synthesize btn_switcher;
@synthesize configData;
@synthesize viewA,viewKwh,viewV,viewW;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    int totalHeight = 35+78*4;
    int viewHeight = self.view.frame.size.height -TABBAR_HEIGHT;
    
    int split = (viewHeight-totalHeight)/6;
    
    NSArray *views = [NSArray arrayWithObjects:btn_switcher,viewKwh,viewW,viewV,viewA, nil];
    int height = split ;
    for (UIView *subview in views) {
        CGRect frame = subview.frame;
        frame.origin.y = height;
        subview.frame = frame;
        height += frame.size.height + split;
    }
    
    
    [self loadData];
}


-(void)loadData
{
    NSInteger statusVal = [data getIntegerValForKey:@"Status"];
    btn_switcher.selected = (statusVal == 1?TRUE:FALSE);
    
    NSDictionary *dictVal = [data objectForKey:@"Value"];
    if (dictVal) {
        labelKwh.text = [dictVal objectForKey:@"kWh"];
        
        labelW.text = [dictVal objectForKey:@"W"];
        
        labelV.text = [dictVal objectForKey:@"V"];
        
        labelA.text = [dictVal objectForKey:@"A"];
    
        return;
    }
    
    [activity startAnimating];
    
    MeterStatusData *meterStatusData = [[MeterStatusData alloc]initWidthZid:[data objectForKey:@"zid"]];
    [meterStatusData getDataWithDataRecivedBlock:^(id xdata) {
        [activity stopAnimating];
        for (NSDictionary *dict in xdata) {
            
            if ([dict objectForKey:@"status"]) {
                if ([[dict objectForKey:@"status"] isEqualToString:@"0"]) {
                    btn_switcher.selected = NO;
                }else{
                    btn_switcher.selected = YES;
                }
            }
            
            int scale = [[dict objectForKey:@"scale"] intValue];
            NSString *mvalue =[dict objectForKey:@"mvalue"];
            if (scale == 0) {
                labelKwh.text = mvalue;
            }else if (scale == 2) {
                labelW.text = mvalue;
            }else if (scale == 4) {
                labelV.text = mvalue;
            }else if (scale == 5) {
                labelA.text = mvalue;
            }
        }
    }];

}

-(ASIHTTPRequest *)createHTTPRequest
{
    NSString *url = @"";
    NSString *zid = [data objectForKey:@"zid"];
    NSString *xchannel = [data objectForKey:@"channel"];
    int value = (btn_switcher.selected)?1:0;
    
    int mid = [[data objectForKey:@"mid"]intValue];
    if (mid ==0){
        url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&OP=%d",zid,value];
    }else{
        url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&OP=%d&Inst=%@",zid,value,([xchannel isEqualToString:@"1"]?@"":xchannel)];
    }
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[GlobalVar createApiUrlAddress:url]]];
    request.delegate = self;
    request.username = [GlobalVar getDataForKey:@"config.username"];
    request.password = [GlobalVar getDataForKey:@"config.password"];
    [request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
    return request;
}


-(IBAction)doSwitch:(id)sender
{
    [activity startAnimating];
    btn_switcher.selected = !btn_switcher.selected;
    
    NSString *zid = [self.data objectForKey:@"ZID"];
    WisDevSwitchSetCmd cmd;
    memset(&cmd, 0, sizeof(WisDevSwitchSetCmd));
    strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String] );
    strcpy(cmd.did, [zid UTF8String]);
    cmd.value = (btn_switcher.selected)?1:0;
    int value = (btn_switcher.selected)?1:0;
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *dStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Switch.cgi?ZID=%@&Value=%d", ipUrl, zid,value];
        [Utitlity commonHTTPMethod:dStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"responseObject:%@",responseObject);
            if (responseObject)
            {
                NSString *state = responseObject[@"state"];
                if (![state isEqualToString:@"Success"])
                {
                    btn_switcher.selected = !btn_switcher.selected;
                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    
    [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_DEV_SWITCH_SET cmdLength:sizeof(WisDevSwitchSetCmd)  withData:&cmd callRecivedBlock:^(id jsondata) {
        
        [activity stopAnimating];
        
        if (jsondata) {
            NSString *state = [jsondata objectForKey:@"state"];
            if (![state isEqualToString:@"Success"]) {
                btn_switcher.selected = !btn_switcher.selected;
            }
        }
        
    }];
    
    //self.httpRequest = [self createHTTPRequest];
    //[self.httpRequest startAsynchronous];
}

- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)xdata
{
    [activity stopAnimating];
    NSString *dataString = [[NSString alloc]initWithData:xdata encoding:NSUTF8StringEncoding];
    dataString = [dataString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    dataString = [dataString lowercaseString];
    if (![dataString isEqualToString:@"success"]) {
        btn_switcher.selected = !btn_switcher.selected;
    }
}

@end
